<template>
  <div class="forgot-view">
    <div class="forgot-container">
      <div class="forgot-card">
        <div class="forgot-header">
          <div class="logo">🔐</div>
          <h1>找回密码</h1>
          <p>通过手机号验证后重置密码</p>
        </div>

        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          class="forgot-form"
          size="large"
          @submit.prevent="handleSubmit"
        >
          <el-form-item prop="phone">
            <el-input
              v-model="form.phone"
              placeholder="请输入手机号"
              :prefix-icon="Phone"
              clearable
            />
          </el-form-item>

          <el-form-item prop="code">
            <el-input v-model="form.code" placeholder="请输入验证码" clearable>
              <template #append>
                <el-button :disabled="countdown > 0 || sending" @click="onSendCode">
                  {{ countdown > 0 ? `${countdown}s` : (sending ? '发送中' : '获取验证码') }}
                </el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item prop="newPassword">
            <el-input
              v-model="form.newPassword"
              type="password"
              placeholder="请输入新密码（至少6位）"
              :prefix-icon="Lock"
              show-password
              clearable
            />
          </el-form-item>

          <el-form-item prop="confirmPassword">
            <el-input
              v-model="form.confirmPassword"
              type="password"
              placeholder="请确认新密码"
              :prefix-icon="Lock"
              show-password
              clearable
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              class="submit-btn"
              :loading="userStore.isLoading"
              @click="handleSubmit"
              native-type="submit"
            >
              提交
            </el-button>
          </el-form-item>

          <div class="back-link">
            <el-link type="primary" @click="$router.push('/login')">返回登录</el-link>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useUserStore } from '@/stores/userStore'
import { ElMessage } from 'element-plus'
import { Phone, Lock } from '@element-plus/icons-vue'
import bgUrl from '@/assets/images/background.png'
import { userApi } from '@/api/user'

const bgUrlCss = `url(${bgUrl})`

const userStore = useUserStore()

const formRef = ref()
const form = reactive({
  phone: '',
  code: '',
  newPassword: '',
  confirmPassword: ''
})

const rules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== form.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const countdown = ref(0)
const sending = ref(false)

const onSendCode = async () => {
  if (sending.value || countdown.value > 0) return
  await formRef.value?.validateField('phone').catch(() => {})
  const phoneValid = /^1\d{10}$/.test(form.phone)
  if (!phoneValid) return
  try {
    sending.value = true
    const res = await userApi.sendResetCode(form.phone)
    if (res.code === 200) {
      ElMessage.success('验证码已发送')
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) clearInterval(timer)
      }, 1000)
    } else {
      ElMessage.error(res.message || '发送失败')
    }
  } catch (e) {
    ElMessage.error('发送失败，请稍后再试')
  } finally {
    sending.value = false
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    const success = await userStore.$patch(async (state) => {
      try {
        state.isLoading = true
        const res = await userApi.resetPasswordByPhone({
          phone: form.phone,
          code: form.code,
          newPassword: form.newPassword
        })
        if (res.code === 200) {
          ElMessage.success('密码重置成功，请使用新密码登录')
          return true
        } else {
          ElMessage.error(res.message || '密码重置失败')
          return false
        }
      } catch (e) {
        ElMessage.error('请求失败，请稍后再试')
        return false
      } finally {
        state.isLoading = false
      }
    })
    if (success) {
      window.setTimeout(() => {
        // 跳转回登录
        location.href = '/login'
      }, 300)
    }
  })
}
</script>

<style scoped>
.forgot-view {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-image: v-bind('bgUrlCss');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed;
  padding: 40px 20px;
}

.forgot-container {
  display: flex;
  justify-content: center;
  max-width: 560px;
  width: 100%;
}

.forgot-card {
  background: white;
  padding: 44px;
  border-radius: 16px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1);
  width: 100%;
}

.forgot-header { text-align: center; margin-bottom: 30px; }
.logo { font-size: 42px; margin-bottom: 12px; }
.forgot-header h1 { font-size: 26px; font-weight: 600; color: #333; margin-bottom: 8px; }
.forgot-header p { color: #666; font-size: 15px; }

.submit-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 500;
  background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
  border: none;
  border-radius: 8px;
}

.back-link { text-align: center; }
</style> 